'''
Created on Nov 20, 2011

@author: Jonathan Herbst
'''

import Error

from google.appengine.ext import db
from google.appengine.api import users

class GameNotActiveError(Error.ModelError): pass

class Game(db.Model):
    creationDate = db.DateTimeProperty(auto_now_add=True, required=True)
    active = db.BooleanProperty(default=True, required=True)
    numRatings = db.IntegerProperty(default=0, required=True)
    avgRating = db.FloatProperty(default=0.0, required=True)
    
    def AddItem(self, paperItem):
        if not self.active:
            raise GameNotActiveError()
        
        user = users.get_current_user()
        if not user:
            raise Error.NotAuthorized()
        
        paper = self.papers.filter("user=", user.user_id()).get()
        if not paper:
            raise Error.NotAuthorized()
        
        paper.AddItem(paperItem)
    
    def NextRound(self):
        if not self.active:
            raise GameNotActiveError()
        
        paper = self.papers.order("-order").get()
        if paper:
            user = paper.user
            for paper in self.papers:
                nextUser = paper.user
                paper.user = user
                user = nextUser
                paper.put()
        
        